<template>
    <p>管理学生</p>
    <div>
        <div class="search-form">
            <el-form :model="searchForm" :rules="rules" inline>
                <el-form-item label="学生ID">
                    <el-input v-model="searchForm.studentId" @keyup.enter="search" placeholder="请输入学生ID"></el-input>
                </el-form-item>
                <el-form-item label="学生姓名">
                    <el-input v-model="searchForm.studentName" @keyup.enter="search" placeholder="请输入学生姓名"></el-input>
                </el-form-item>
                <el-form-item style="margin-bottom: 40px">
                    <el-button type="primary" @click="search">搜索</el-button>
                    <el-button @click="resetForm">重置</el-button>
                </el-form-item>
            </el-form>
        </div>
        <!-- <el-form-item class="search-form" style="display: flex;flex-direction: row">
            <el-input style="line-height: 32px;flex: 0.88;margin-right: 4px" type="text" v-model="searchQuery" placeholder="输入关键词进行搜索,关键词间用&隔开，第一个部分为学号，第二个部分为姓名" />
            <el-button style="line-height: 32px;flex: 0.06;margin-top: 0px" @click="search">搜索</el-button>
        </el-form-item> -->
        <div class="inputDiv">
            <el-form-item label="姓名">
                <el-input v-model="addForm.name" />
            </el-form-item>
            <el-form-item label="账号">
                <el-input v-model="addForm.studentID" />
            </el-form-item>
        </div>
        <div class="import_div" style="display: flex;flex-direction: row;">
            <el-upload v-model:file-list="fileList" class="upload-demo" action="http://8.130.42.115:8000/student/upload"
                :headers="headers" :data="loadFileParams" :on-preview="handlePreview" :on-exceed="handleExceed">
                <el-button class="import-el-button" style="margin-left: -110px">批量导入</el-button>
            </el-upload>
            <el-button class="import-el-button" @click="addPerson()" style="margin-left: 0px">手动导入</el-button>
        </div>
        <div style="margin-left: 303px; margin-bottom: 8px;display: flex;flex-direction: row">
            <el-button class="import-el-button" @click="downLoadStu()">下载名单</el-button>
            <el-button @click="deleteBatchTeacher" style="margin-top: 0px">批量删除</el-button>
        </div>
        <el-table ref="multipleTableRef" :data="displayedPeople" style="width: 100%;"
            @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" />
            <el-table-column fixed label="操作" width="360">
                <template #default="{ row }">
                    <el-button v-if="matchUrlData === 'stu'" link type="primary" size="small"
                        @click="editPerson(row)">编辑</el-button>
                    <el-dialog title="编辑学生信息" v-model="dialogFormVisible" :before-close="handleClose">
                        <el-form :model="form">
                            <el-form-item label="学生姓名" :label-width="formLabelWidth">
                                <el-input v-model="form.name" autocomplete="off" />
                            </el-form-item>
                            <el-form-item label="学生ID" :label-width="formLabelWidth">
                                <el-input v-model="form.studentID" autocomplete="off" />
                            </el-form-item>
                        </el-form>
                        <template #footer>
                            <span class="dialog-footer" @click="dialogFormVisible = false">
                                <el-button>取消</el-button>
                                <el-button type="primary" @click="saveEdit(row)">
                                    确认
                                </el-button>
                            </span>
                        </template>
                    </el-dialog>
                    <el-button link type="primary" size="small" @click="deleteSingleStudentFun(row)">删除</el-button>
                </template>
            </el-table-column>
            <el-table-column property="name" label="学生姓名" />
            <el-table-column property="studentID" label="学生ID" show-overflow-tooltip />
        </el-table>
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
            :page-sizes="[5, 10, 20, 30, 40]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
            :total="people.length">
        </el-pagination>
        <div style="margin-top: 20px">

        </div>
    </div>
</template>
  
<script setup>
import { ref, toRefs, reactive, onMounted, watch } from 'vue';
import { ElNotification, ElDialog, ElForm, ElFormItem, ElInput, ElButton ,ElPagination} from 'element-plus';
import XLSX from 'xlsx';
import { useStore } from '../../Admin/store'
import { useStudentListStore } from '@/stores/studentList.js'
import { ElTable, ElUpload } from 'element-plus'
import { useClassIDStore } from '@/stores/classID.js'
import { addSingleStudent, deleteSingleStudent, editorStudentInfo, deleteBatchStudents, selectSudentInfoService, allCourseStudentAttend, deleteSingleStudentInClass, deleteBatchStudentsInClass } from '@/api/adminApi/allAdmin'
import { useRoute } from 'vue-router';
import { useTokenStore } from '@/stores/token.js';
let tokenStore = useTokenStore()
const headers = ref({
    token: tokenStore.token.token
})
const searchForm = ref({
    studentId: '',
    studentName: ''
});
const resetForm = () => {
    searchForm.value.studentId = '';
    searchForm.value.studentName = '';
};
const router = useRoute();
const classIDstore = useClassIDStore();
const studentistStore = useStudentListStore()
const store = useStore()
const fileList = ref()
const displayedPeople = ref([]); // 当前显示的数据
const currentPage = ref(1);
const pageSize = ref(10);

const handleSizeChange = (val) => {
    pageSize.value = val;
    currentPage.value = 1;
    displayedPeople.value = paginateData();
};

const handleCurrentChange = (val) => {
    currentPage.value = val;
    displayedPeople.value = paginateData();
};

const paginateData = () => {
    const startIndex = (currentPage.value - 1) * pageSize.value;
    const endIndex = startIndex + pageSize.value;
    return people.value.slice(startIndex, endIndex);
};
onMounted(() => {
    displayedPeople.value = paginateData();
})
watch(
    () => studentistStore.studentList,
    () => people.value = studentistStore.studentList,
    { deep: true }
)
const props = defineProps({
    tableData: Array
})
const people = ref(studentistStore.studentList);
const form = ref({
    studentID: '',
    name: '',
    editIndex: 0
});
const addForm = ref({
    name: '',
    studentID: ''
});
const multipleTableRef = ref()
const dialogFormVisible = ref(false);
const addPerson = async () => {
    const data = {
        name: addForm.value.name,
        studentID: addForm.value.studentID,
        password: '123456',
        classID: classIDstore.classID
    };
    people.value.push(data)
    addForm.value = {}
    await addSingleStudent(data)
};
const loadFileParams = ref({
    classID: classIDstore.classID
})
//保存多选行的信息
const selectionRow = ref([])
const handleSelectionChange = (section) => {
    selectionRow.value = section
    console.log(selectionRow.value, 'selectionRow')
}
//批量删除
const deleteBatchTeacher = async () => {
    const data = []
    selectionRow.value.map((item, index) => {
        data.push(item.studentID)
        people.value.map((list, idx) => {
            if (item.studentID === list.studentID)
                people.value.splice(idx, 1)
        })
    })
    //data數據格式不對！！！！！！
    await deleteBatchStudentsInClass(data)
}
const editPerson = async (row) => {
    // 处理选中行数据
    form.value.name = row.name;
    form.value.studentID = row.studentID;
    dialogFormVisible.value = true;
}
//删除单个學生
const deleteSingleStudentFun = async (row) => {
    const data = {
        classID: classIDstore.classID,
        studentID: row.studentID
    }
    const index = people.value.findIndex(item => item.studentID === row.studentID);
    people.value.splice(index, 1)
    await deleteSingleStudentInClass(data)
};
//保存编辑内容
const saveEdit = async () => {
    const data = {
        name: form.value.name,
        password: "123456",//设为初始值
        studentID: form.value.studentID
    }
    await editorStudentInfo(data)
    const index = people.value.findIndex((item) => item.studentID === form.value.studentID)
    people.value[index].name = form.value.name
}
const searchQuery = ref('');
const search = async () => {
    let result={
        studentID:searchForm.value.studentId,
        name:searchForm.value.studentName,
        pageSize:20,
        pageNum:1
    }
    const res = await selectSudentInfoService(result)
    displayedPeople.value = res.data
    people.value=res.data
};
const handleCloseDialog = (done) => {
    form.value.studentID = '';
    form.value.teacherName = '';
    done();
};

// 将响应式数据转换为可解构的对象
const { value: reactivePeople } = toRefs(people);
const downLoadStu = () => {
    const worksheet = XLSX.utils.json_to_sheet(people.value);
    const workbook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
    XLSX.writeFile(workbook, 'students.xlsx');
}
const handleFileUpload = (event) => {
    const file = event.target.files[0];
    const reader = new FileReader();
    reader.onload = (e) => {
        const data = new Uint8Array(e.target.result);
        const workbook = XLSX.read(data, { type: 'array' });
        const worksheet = workbook.Sheets[workbook.SheetNames[0]];
        const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });

        // 将数据存入ref
        people.value = jsonData.map((row, index) => {
            if (index === 0) return null; // 跳过表头行
            const [id, studentID, studentName] = row;
            return { id, studentID, studentName };
        }).filter(Boolean);
    };

    reader.readAsArrayBuffer(file);
}

</script>
  
<style>
.dialog-footer {
    display: flex;
    justify-content: flex-end;
}

.import_div {
    display: inline-block;
    margin-left: 28%;
}
</style>
  
  <!-- 引入 Element Plus 组件库 -->
<script>
export default {
    components: {
        ElNotification,
        ElDialog,
        ElForm,
        ElFormItem,
        ElInput,
        ElButton,
    },
};
</script>@/api/adminApi/allAdmin